package com.example.yuwei.mediaplayer.view;

import android.Manifest;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.yuwei.mediaplayer.timeutil.Tools;
import com.example.yuwei.mediaplayer.presenter.MusicPresenter;
import com.example.yuwei.mediaplayer.R;

import java.util.ArrayList;
import java.util.Map;

import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;

public class MainActivity extends AppCompatActivity {
    private final static int ORDER_PLAY = 0;
    private final static int RANDOM_PLAY = 1;
    private final static int LOOP_PLAY = 2;
    private static int play_Mode = ORDER_PLAY;
    private boolean isSetting = false;
    private boolean isOver = false;
    private String title = "";
    private String currentTime = "";
    private String totalTime = "";
    private int currentPosition = 0;
    private int duration = 0;
    private ArrayList<Map<String, Object>> musicList;
    private Tools tools;
    private MusicPresenter musicPresenter;
    private String TAG = "uiviews";
    private NotificationManager notificationManager = null;
    private RemoteViews views;
    private NotificationCompat.Builder mBuidler;

    //定义控件
    private ListView lv_musicList;
    private SeekBar sb_TimeBar;
    private Button btn_Play;
    private Button btn_Previous;
    private Button btn_Next;
    private Button btn_Play_Mode;
    private TextView tv_Total_Time;
    private TextView tv_Progress_Time;
    private TextView tv_music_title;
    private Button btn_Exit;
    /**
     * onBind启动服务，如用startService启动服务会被系统清理
     */
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
    /**
     * 利用Handler来刷新UI
     * 如果直接在activity中创建线程刷新UI有错误，文字类无法设置
     */
    private Handler mHandler = new Handler();
    public Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (musicPresenter.isPlaying() && !isSetting) {
                currentPosition = musicPresenter.getCurrentPosition();
            }
            setInfoText();
            updateNotification();
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        createNotification();
        init();
    }

    public void init() {
        //获取控件
        sb_TimeBar = findViewById(R.id.sb_time_progress);
        lv_musicList = findViewById(R.id.musicListView);

        btn_Previous = findViewById(R.id.btn_previous);
        btn_Play = findViewById(R.id.btn_play_pause);
        btn_Next = findViewById(R.id.btn_next);
        btn_Play_Mode = findViewById(R.id.btn_play_mode);
        btn_Exit = findViewById(R.id.btn_exit);

        tv_Total_Time = findViewById(R.id.tv_time_total);
        tv_Progress_Time = findViewById(R.id.tv_time_progressing);
        tv_music_title = findViewById(R.id.tv_music_title);

        musicPresenter = MusicPresenter.getInstance();
        tools = new Tools();


        //注册监听屏幕的广播
        final OnePixelReceiver mOnepxReceiver = new OnePixelReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.SCREEN_OFF");
        intentFilter.addAction("android.intent.action.SCREEN_ON");
        intentFilter.addAction("android.intent.action.USER_PRESENT");
        registerReceiver(mOnepxReceiver, intentFilter);

        //判断是否取得授权
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
                permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new
                    String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        } else {
            musicList = musicPresenter.getMusicList(getBaseContext());
        }
        //定义SimpleAdapter
        SimpleAdapter mSimpleAdapter = new SimpleAdapter(
                this,
                musicList,
                R.layout.music,
                new String[]{"Title", "Artist", "Size", "Duration"},
                new int[]{R.id.tv_music_title, R.id.tv_music_artist,
                        R.id.tv_music_size, R.id.tv_music_duration}
        );
        //向listview里加载音乐列表
        lv_musicList.setAdapter(mSimpleAdapter);
        lv_musicList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.setAction("play");
                intent.setPackage(getPackageName());
                intent.putExtra("type","select");
                intent.putExtra("position",position);
                startService(intent);
                currentPosition = 0;
                setInfoText();
            }
        });
        //启动后台服务
        final Intent intent = new Intent();
        intent.setAction("play");
        intent.setPackage(getPackageName());
        bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);
        startService(intent);
        musicPresenter.fisrtOpen();
        setInfoText();
        //播放暂停按钮响应
        btn_Play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setInfoText();
                Intent intent = new Intent();
                intent.setAction("play");
                intent.setPackage(getPackageName());
                intent.putExtra("type","playOrPause");
                startService(intent);
            }
        });

        //上下一曲按钮响应
        btn_Previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentPosition = 0;
                setInfoText();
                Intent intent = new Intent();
                intent.setAction("play");
                intent.setPackage(getPackageName());
                intent.putExtra("type","previous");
                startService(intent);
            }
        });
        btn_Next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentPosition = 0;
                setInfoText();
                Intent intent = new Intent();
                intent.setAction("play");
                intent.setPackage(getPackageName());
                intent.putExtra("type","next");
                startService(intent);
            }
        });

        //进度条响应
        sb_TimeBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    currentPosition = progress;
                    isSetting = true;
                    musicPresenter.setProgress(currentPosition);
                    setInfoText();
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Log.i(TAG, "onStopTrackingTouch: ");
                musicPresenter.progressPlay();
                Intent intent = new Intent();
                intent.setAction("play");
                intent.setPackage(getPackageName());
                intent.putExtra("type","progress");
                startService(intent);
                isSetting = false;
            }
        });
        //模式按钮响应
        btn_Play_Mode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                play_Mode = musicPresenter.setMode();
                setInfoText();
            }
        });
        //退出按键响应
        btn_Exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notificationManager.cancel(0);
                unbindService(serviceConnection);
                unregisterReceiver(mOnepxReceiver);
                stopService(intent);
                finish();
                onDestroy();
            }
        });
        //创建刷新UI的线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!isOver) {
                    mHandler.post(runnable);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        System.exit(1);
                    }
                }
            }
        }).start();
    }
    /**
     * 请求权限申请
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    musicList = musicPresenter.getMusicList(getBaseContext());
                } else {
                    Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    /**
     * 设置UI
     */
    public void setInfoText() {
        currentTime = tools.toTime(currentPosition);
        duration = musicPresenter.getDuration();
        totalTime = tools.toTime(duration);
        sb_TimeBar.setProgress(currentPosition);
        sb_TimeBar.setMax(duration);
        tv_Progress_Time.setText(currentTime);
        tv_Total_Time.setText(totalTime);
        title = musicPresenter.getTitle();
        tv_music_title.setText(title);
        if (!musicPresenter.isPlaying()) {
            btn_Play.setText(getResources().getString(R.string.play));
        } else {
            btn_Play.setText(getResources().getString(R.string.pause));
        }
        if (play_Mode == ORDER_PLAY) {
            btn_Play_Mode.setText(getResources().getString(R.string.play_mode_order_play));
            return;
        }
        if (play_Mode == RANDOM_PLAY) {
            btn_Play_Mode.setText(getResources().getString(R.string.play_mode_random_play));
            return;
        }
        if (play_Mode == LOOP_PLAY) {
            btn_Play_Mode.setText(getResources().getString(R.string.play_mode_single_loop));
            return;
        }
    }
    public void createNotification() {

        mBuidler = new NotificationCompat.Builder(this);
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationChannel channel;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channel = new NotificationChannel("10086", "音乐", NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(channel);
            mBuidler.setChannelId("10086");
        }
        Intent backActivityplay = new Intent(this,MainActivity.class);
        Intent notificationPreviousIntent = new Intent(this, PlayService.class);
        notificationPreviousIntent.putExtra("type", "previous");
        Intent notificationNextIntent = new Intent(this, PlayService.class);
        notificationNextIntent.putExtra("type", "next");
        Intent notificationPlayIntent = new Intent(this, PlayService.class);
        notificationPlayIntent.putExtra("type", "playOrPause");
        PendingIntent backActivityplayPI = PendingIntent.getActivity
                (this,3,backActivityplay,FLAG_UPDATE_CURRENT);
        PendingIntent notifiactionPreviousPI = PendingIntent.getService
                (this, 0, notificationPreviousIntent, FLAG_UPDATE_CURRENT);
        PendingIntent notifiactionPlayPI = PendingIntent.getService
                (this, 1, notificationPlayIntent, FLAG_UPDATE_CURRENT);
        PendingIntent notifiactionNextPI = PendingIntent.getService
                (this, 2, notificationNextIntent, FLAG_UPDATE_CURRENT);

        views = new RemoteViews(getPackageName(), R.layout.layout_notification);
        views.setOnClickPendingIntent(R.id.btn_notification_previous, notifiactionPreviousPI);
        views.setOnClickPendingIntent(R.id.btn_notification_play, notifiactionPlayPI);
        views.setOnClickPendingIntent(R.id.btn_notification_next, notifiactionNextPI);
        mBuidler.setContentTitle("musictitle")
                .setContentText("musictext")
                .setSmallIcon(R.mipmap.musicicon)
                .setAutoCancel(true)
                .setContent(views)
                .setOngoing(true)
                .setContentIntent(backActivityplayPI);
        notificationManager.notify(0, mBuidler.build());
    }
    public void updateNotification() {
        views.setTextViewText(R.id.tv_notification_title, musicPresenter.getTitle());
        if (!musicPresenter.isPlaying()) {
            views.setTextViewText(R.id.btn_notification_play, getResources().getString(R.string.play));
        } else {
            views.setTextViewText(R.id.btn_notification_play, getResources().getString(R.string.pause));
        }
        notificationManager.notify(0, mBuidler.build());
    }

    /**
     * 重写返回建不关闭Activity
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "onDestroy: MainActivity");
        isOver = true;
        super.onDestroy();
    }
    /**
     * Created by Administrator on 2017/7/10.
     * 监听屏幕状态的广播
     */
    public class OnePixelReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                //屏幕关闭启动1像素Activity
                Log.i(TAG, "onReceive: 屏幕关闭");
                Intent it = new Intent(context, OnePiexlActivity.class);
                it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(it);
            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {   
                //屏幕打开 结束1像素
                Log.i(TAG, "onReceive: 屏幕打开");
                context.sendBroadcast(new Intent("finish"));
                Intent main = new Intent(Intent.ACTION_MAIN);
                main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                main.addCategory(Intent.CATEGORY_HOME);
                context.startActivity(main);
            }
        }
    }
}

